import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  DatePicker,
  Spin,
  Tabs,
  Col,
  Row,
  Image,
  InputNumber,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import iqcService, { type PageListReq } from "@/api/services/qms/iqcService";
import type { QmsIqc } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import QmsIqcDetailPage, { type QmsIqcDetailHandles } from "./iqcDetail";
import CustomTable from "@/components/grid/CustomTable";
import SingleSupplierSelector from "@/pages/components/selector/SingleSupplierSelect";
import SingleUserSelector from "@/pages/components/selector/SingleUserSelect";
import SingleMaterialSelector from "@/pages/components/selector/SingleMaterialSelect";

import dayjs from "dayjs";

import AcceptImg from "@/assets/images/accept.png";
import RejectImg from "@/assets/images/reject.png";
import PrepareImg from "@/assets/images/prepare.png";
import { ExportOutlined, UserAddOutlined } from "@ant-design/icons";

const { TextArea } = Input;

// 状态值 -> 图片映射
const statusImages: Record<string, string> = {
  prepare: PrepareImg,
  ok: AcceptImg,
  ng: RejectImg,
};

export default function QmsIqcPage() {
  const iqcDetailRef = useRef<QmsIqcDetailHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    code: undefined,
    sourceType: undefined,
    sourceCode: undefined,
    materialId: undefined,
    checkResult: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<QmsIqc[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<QmsIqc | null>(null);
  const [userSelectVisiable, setUserSelectVisiable] = useState(false);
  const [supplierSelectVisiable, setSupplierSelectVisiable] = useState(false);
  const [materialSelectVisiable, setMaterialSelectVisiable] = useState(false);

  const [form] = Form.useForm();
  // 监听 checkResult 字段
  const checkResult = Form.useWatch("checkResult", form);

  const handleValuesChange = (_: any, allValues: any) => {
    const { qtyCheck = 0, qtyUnqualified = 0 } = allValues;
    const qualified = Math.max(qtyCheck - qtyUnqualified, 0); // 不让负数出现
    form.setFieldsValue({ qtyQualified: qualified });
  };

  // 如果 checkResult 为空，就使用 'prepare' 作为默认值
  const imageKey =
    checkResult && checkResult.trim() !== "" ? checkResult : "prepare";

  const [isView, setIsView] = useState(true);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const checkResultOptions = useDictionary("check_result");
  const statusOptions = useDictionary("common_order_status");
  const sourceTypeOptions = useDictionary("sys_order_type");

  const columns: ColumnsType<QmsIqc> = [
    {
      title: "检验单号",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "来源单据类型",
      width: 120,
      key: "sourceType",
      dataIndex: "sourceType",
      render: (_, record) => (
        <TableDictTag
          dictCode="sys_order_type"
          value={record.sourceType ?? ""}
        />
      ),
    },
    {
      title: "来源单据号",
      width: 120,
      key: "sourceCode",
      dataIndex: "sourceCode",
    },
    {
      title: "单据状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="common_order_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "供应商",
      width: 120,
      key: "supplierName",
      dataIndex: "supplierName",
    },
    {
      title: "物料编码",
      width: 120,
      key: "materialCode",
      dataIndex: "materialCode",
    },
    {
      title: "物料名称",
      width: 120,
      key: "materialName",
      dataIndex: "materialName",
    },
    {
      title: "物料规格",
      width: 120,
      key: "materialSpec",
      dataIndex: "materialSpec",
    },
    {
      title: "本次接收数量",
      width: 120,
      key: "qtyReceipt",
      dataIndex: "qtyReceipt",
    },
    {
      title: "本次检测数量",
      width: 120,
      key: "qtyCheck",
      dataIndex: "qtyCheck",
    },
    {
      title: "不合格数",
      width: 120,
      key: "qtyUnqualified",
      dataIndex: "qtyUnqualified",
    },
    {
      title: "检测结果",
      width: 120,
      key: "checkResult",
      dataIndex: "checkResult",
      render: (_, record) => (
        <TableDictTag
          dictCode="check_result"
          value={record.checkResult ?? ""}
        />
      ),
    },
    {
      title: "来料日期",
      width: 120,
      key: "receiptDate",
      dataIndex: "receiptDate",
    },
    {
      title: "检测日期",
      width: 120,
      key: "inspectDate",
      dataIndex: "inspectDate",
    },
    {
      title: "检测人员",
      width: 120,
      key: "inspectorName",
      dataIndex: "inspectorName",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    iqcService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (qmsIqc: QmsIqc) => {
    setEditingData(qmsIqc);
    form.setFieldsValue(qmsIqc);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (qmsIqc: QmsIqc) => {
    setEditingData(qmsIqc);
    form.setFieldsValue(qmsIqc);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: QmsIqc) => {
    try {
      setSubmitLoading(true);

      //来料检验项明细
      const deleteIqcDetailIds = iqcDetailRef.current?.getDeleteIds();
      const addIqcDetails = iqcDetailRef.current?.getAddList();
      const updateIqcDetails = iqcDetailRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteIqcDetailIds: deleteIqcDetailIds,
        addIqcDetails: addIqcDetails,
        updateIqcDetails: updateIqcDetails,
      };
      if (editingData) {
        await iqcService.update(data);
        toast.success("更新来料检验单成功");
      } else {
        await iqcService.add(data);
        toast.success("创建来料检验单成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await iqcService.remove(selectedRowKeys);
      toast.success("删除来料检验单成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const showSupplierSelect = () => {
    setSupplierSelectVisiable(true);
  };

  const handleSelectSupplier = (supplier: any) => {
    form.setFieldsValue({
      supplierId: supplier?.id,
      supplierName: supplier?.supplier_name,
    });
    setSupplierSelectVisiable(false);
  };

  const showUserSelect = () => {
    setUserSelectVisiable(true);
  };

  const handleSelectUser = (user: any) => {
    form.setFieldsValue({
      inspector: user?.id,
      inspectorName: user?.name,
    });
    setUserSelectVisiable(false);
  };

  const openSelectMaterial = (id: React.Key) => {
		setMaterialSelectVisiable(true);
	};

	const handleSelectMaterial = (material: any) => {
		setMaterialSelectVisiable(false);
		if (material) {
			const { id, materialCode, materialName, spec } = material;
			form.setFieldsValue({
				materialId: id,
				materialCode: materialCode,
				materialName: materialName,
				materialSpec: spec,
			});
		}
	};

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="code" label="检验单号">
            <Input allowClear placeholder="请输入检验单号" />
          </Form.Item>

          <Form.Item name="sourceCode" label="来源单据号">
            <Input allowClear placeholder="请输入来源单据号" />
          </Form.Item>

          <Form.Item name="materialId" label="物料编码">
            <Input allowClear placeholder="请输入物料编码" />
          </Form.Item>

          <Form.Item name="checkResult" label="检测结果">
            <Select
              options={checkResultOptions}
              allowClear
              style={{ width: 170 }}
              placeholder="请选择检测结果"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑来料检验单" : "新增来料检验单"}
        width={1000}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button
                type="primary"
                loading={submitLoading}
                onClick={() => form.submit()}
              >
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onValuesChange={handleValuesChange}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="code" label="检验单号">
                <Input placeholder="检验单号自动生成" disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="checkResult"
                rules={[
                  {
                    required: true,
                    message: "请填写检测结果",
                  },
                ]}
                label="检测结果"
              >
                <Select
                  placeholder="请填写检测结果"
                  options={checkResultOptions}
                  allowClear
                />
              </Form.Item>
              <Form.Item name="status" label="单据状态" hidden>
                <Select options={statusOptions} allowClear />
              </Form.Item>
            </Col>
            <Image
              src={statusImages[imageKey]}
              width={80}
              alt={imageKey}
              preview={false}
              style={{
                position: "absolute",
                right: -50, // 靠右
                top: "30%", // 垂直居中
                transform: "translateY(-50%)",
              }}
            />
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="sourceType" label="来源单据类型">
                <Select
                  options={sourceTypeOptions}
                  allowClear
                  placeholder="请选择来源单据类型"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="sourceCode" label="来源单据编号">
                <Input placeholder="请输入来源单据编号" allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="supplierId" label="供应商" hidden>
                <Input />
              </Form.Item>
              <Form.Item
                name="supplierName"
                label="供应商"
                rules={[
                  {
                    required: true,
                    message: "请填写供应商",
                  },
                ]}
              >
                <Input.Search
                  placeholder="请输入供应商"
                  allowClear
                  enterButton={<UserAddOutlined />}
                  onSearch={showSupplierSelect}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="物料编码" name="materialCode" rules={[{ required: true, message: "请选择物料编码" }]}>
								<Input.Search
									placeholder="请选择生产物料"
									allowClear
									enterButton={<ExportOutlined />}
									onSearch={openSelectMaterial}
								/>
							</Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="materialName" label="物料名称">
                <Input placeholder="请输入物料名称" disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="materialSpec" label="物料规格">
                <Input placeholder="请输入物料规格" disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="qtyReceipt"
                label="本次接收数量"
                rules={[
                  {
                    required: true,
                    message: "请填写本次接收数量",
                  },
                ]}
              >
                <InputNumber
                  placeholder="请输入本次接收数量"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="qtyMinCheck" label="最低检测数">
                <InputNumber
                  placeholder="请输入最低检测数"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="qtyMaxUnqualified" label="最大不合格数">
                <InputNumber
                  placeholder="请输入最大不合格数"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="qtyCheck"
                label="本次检测数量"
                rules={[
                  {
                    required: true,
                    message: "请填写本次检测数量",
                  },
                ]}
              >
                <InputNumber
                  placeholder="请输入本次检测数量"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="qtyUnqualified" label="不合格数">
                <InputNumber
                  placeholder="请输入不合格数"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="qtyQualified" label="合格数">
                <InputNumber disabled style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="receiptDate"
                label="来料日期"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="inspectDate"
                label="检测日期"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="inspector" label="检测人员" hidden>
                <Input />
              </Form.Item>
              <Form.Item
                name="inspectorName"
                label="检测人员"
                rules={[
                  {
                    required: true,
                    message: "请选择检测人员",
                  },
                ]}
              >
                <Input.Search
                  placeholder="请选择检测人员"
                  allowClear
                  enterButton={<UserAddOutlined />}
                  onSearch={showUserSelect}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 2 }}
                wrapperCol={{ span: 22 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1  ",
                label: "来料检验项明细",
                children: (
                  <QmsIqcDetailPage
                    ref={iqcDetailRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>

      {/* 用户选择器 */}
      <SingleUserSelector
        open={userSelectVisiable}
        onCancel={() => setUserSelectVisiable(false)}
        onOk={(selectUser) => handleSelectUser(selectUser)}
      />

      {/* 供应商选择器 */}
      <SingleSupplierSelector
        open={supplierSelectVisiable}
        onCancel={() => setSupplierSelectVisiable(false)}
        onOk={(item) => handleSelectSupplier(item)}
      />

      			{/* 物料选择器 */}
			<SingleMaterialSelector
				open={materialSelectVisiable}
				onCancel={() => setMaterialSelectVisiable(false)}
				onOk={(item) => handleSelectMaterial(item)}
			/>
    </Spin>
  );
}
